package com.api.controller;

import com.api.entity.MenuRight;
import com.api.entity.Menus;
import com.api.entity.UserRole;
import com.api.log.Log;
import com.api.mapper.MenusMapper;
import com.api.utils.Result;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static com.api.entity.table.MenuRightTableDef.MENU_RIGHT;
import static com.api.entity.table.MenusTableDef.MENUS;
import static com.api.entity.table.RoleRightTableDef.ROLE_RIGHT;
import static com.api.entity.table.UserRoleTableDef.USER_ROLE;

/**
 * @Author: yangsf
 * @CreateDate: 2024/9/24
 */

@Slf4j
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController{

    @Autowired
    MenusMapper menusMapper;

    /**
     * 获取菜单
     * 接口：/menu/getList
     * @param kind : 0.全部菜单 1.当前登录用户的菜单
     * @return
     */
    @Log("获取菜单")
    @RequestMapping("/getList")
    public Result getList(Integer kind, Long roleId){
        //kind: 0.获取全部菜单（树形结构,包含按钮） 1.获取当前登录用户的菜单(树形结构,不包含按钮)
        // 2.获取指定角色的菜单权限(树形结构,不包含按钮) 3.获取指定角色的菜单权限(树形结构,包含按钮)
        if(null == kind){
            return Result.err("非法请求");
        }

        List<Menus> menus = new ArrayList<Menus>();
//        @RelationManyToOne(selfField = "parentId", targetField = "id")
//        private Menus parent;
//
//        @RelationOneToMany(selfField = "id", targetField = "parentId")
//        private List<Menus> children;
//
//        @Column(value = "父级菜单名称，如果父级为0，则显示为：顶级父目录",ignore = true)
//        private String parentName;
        //kind:0.获取全部菜单（树形结构,包含按钮）
        if(kind == 0){
            QueryWrapper qw = QueryWrapper.create();
            qw.where(MENUS.PARENT_ID.eq(0))
                    .and(MENUS.KIND.eq(1))
                    .and(MENUS.STATUS.eq(1))
                    .and(MENUS.MENU_TYPE.in(new int[]{1,2}))
                    .orderBy(MENUS.SORT_NUM,true);
            menus = menusMapper.selectListByQuery(qw);
            if(menus.size()>0){
                for(Menus e : menus){
                    e.setParentName("顶级父目录");
                    QueryWrapper cqw = QueryWrapper.create();
                    cqw.where(MENUS.PARENT_ID.eq(e.getId()))
                            .and(MENUS.STATUS.eq(1))
                            .and(MENUS.MENU_TYPE.in(new int[]{2,3}));
                    cqw.orderBy(MENUS.SORT_NUM,true);
                    List<Menus> list = menusMapper.selectListByQuery(cqw);
                    if(list.size()>0){
                        for(Menus btn : list){
                            if(null != btn.getParentId() && btn.getParentId().intValue() > 0){
                                btn.setParentName(e.getTitle());
                            }
                            else{
                                btn.setParentName("顶级父目录");
                            }
                            QueryWrapper bq = QueryWrapper.create();
                            bq.where(MENUS.PARENT_ID.eq(btn.getId()))
                                    .and(MENUS.STATUS.eq(1))
                                    .and(MENUS.MENU_TYPE.in(new int[]{3}));
                            bq.orderBy(MENUS.SORT_NUM,true);
                            List<Menus> btns = menusMapper.selectListByQuery(bq);
                            if(btns.size()>0){
                                for(Menus b : btns){
                                    if(null != btn.getParentId() && btn.getParentId().intValue() > 0){
                                        b.setParentName(btn.getTitle());
                                    }
                                    else{
                                        b.setParentName("顶级父目录");
                                    }
                                }
                            }
                            btn.setChildren(btns);
                        }
                    }
                    e.setChildren(list);
                }
            }
        }
        //kind:1.获取当前登录用户的菜单(树形结构,不包含按钮)
        else if (kind == 1) {
            Integer roleType = getRoleType();
            if(roleType > 20){
                Long userId = getUserId();
                List<Long> longs = MenuRight.create()
                        .select(MENU_RIGHT.MENU_ID)
                        .where(MENU_RIGHT.KIND.eq(2).and(MENU_RIGHT.RELL_ID.eq(userId)))
                        .or(MENU_RIGHT.KIND.eq(1).and(MENU_RIGHT.RELL_ID.in(
                                UserRole.create()
                                        .select(USER_ROLE.ROLE_ID)
                                        .where(USER_ROLE.USER_ID.eq(userId))
                                        .and(USER_ROLE.STATUS.eq(1))
                                        .listAs(Long.class)
                        )))
                        .and(MENU_RIGHT.STATUS.eq(1))
                        .listAs(Long.class);
                if(longs.size()>0){
                    QueryWrapper qw = QueryWrapper.create();
                    qw.where(MENUS.PARENT_ID.eq(0))
                            .and(MENUS.KIND.eq(1))
                            .and(MENUS.STATUS.eq(1))
                            .and(MENUS.MENU_TYPE.in(new int[]{1,2}))
                            .and(MENUS.ID.in(longs))
                            .orderBy(MENUS.SORT_NUM,true);
                    menus = menusMapper.selectListByQuery(qw);
                    if(menus.size()>0){
                        for(Menus e : menus){
                            QueryWrapper cqw = QueryWrapper.create();
                            cqw.where(MENUS.PARENT_ID.eq(e.getId()))
                                    .and(MENUS.STATUS.eq(1))
                                    .and(MENUS.MENU_TYPE.in(new int[]{1,2}));
                            if(longs.size()>0){
                                cqw.and(MENUS.ID.in(longs));
                            }
                            cqw.orderBy(MENUS.SORT_NUM,true);
                            List<Menus> list = menusMapper.selectListByQuery(cqw);
                            e.setChildren(list);
                        }
                    }
                }
            }
            else{
                QueryWrapper qw = QueryWrapper.create();
                qw.where(MENUS.PARENT_ID.eq(0))
                        .and(MENUS.KIND.eq(1))
                        .and(MENUS.STATUS.eq(1))
                        .and(MENUS.MENU_TYPE.in(new int[]{1,2}))
                        .orderBy(MENUS.SORT_NUM,true);
                menus = menusMapper.selectListByQuery(qw);
                if(menus.size()>0){
                    for(Menus e : menus){
                        QueryWrapper cqw = QueryWrapper.create();
                        cqw.where(MENUS.PARENT_ID.eq(e.getId()))
                        .and(MENUS.STATUS.eq(1))
                        .and(MENUS.MENU_TYPE.in(new int[]{1,2}));
                        cqw.orderBy(MENUS.SORT_NUM,true);
                        List<Menus> list = menusMapper.selectListByQuery(cqw);
                        e.setChildren(list);
                    }
                }
            }
        }
        //kind:2.获取指定角色的菜单权限(树形结构,不包含按钮)
        else if(kind == 2){
            if(null == roleId){
                return Result.err("未获取到角色信息");
            }
            List<Long> longs = MenuRight.create()
                    .select(MENU_RIGHT.MENU_ID)
                    .where(MENU_RIGHT.KIND.eq(1).and(MENU_RIGHT.RELL_ID.eq(roleId)))
                    .and(MENU_RIGHT.STATUS.eq(1))
                    .listAs(Long.class);
            if(longs.size()>0){
                QueryWrapper qw = QueryWrapper.create();
                qw.where(MENUS.PARENT_ID.eq(0))
                        .and(MENUS.KIND.eq(1))
                        .and(MENUS.STATUS.eq(1))
                        .and(MENUS.MENU_TYPE.in(new int[]{1,2}))
                        .and(MENUS.ID.in(longs))
                        .orderBy(MENUS.SORT_NUM,true);
                menus = menusMapper.selectListByQuery(qw);
                if(menus.size()>0){
                    for(Menus e : menus){
                        QueryWrapper cqw = QueryWrapper.create();
                        cqw.where(MENUS.PARENT_ID.eq(e.getId()))
                                .and(MENUS.STATUS.eq(1))
                                .and(MENUS.MENU_TYPE.in(new int[]{1,2}));
                        if(longs.size()>0){
                            cqw.and(MENUS.ID.in(longs));
                        }
                        cqw.orderBy(MENUS.SORT_NUM,true);
                        List<Menus> list = menusMapper.selectListByQuery(cqw);
                        e.setChildren(list);
                    }
                }
            }
        }
        //kind:3.获取指定角色的菜单权限(树形结构,包含按钮)
        else if(kind == 3){
            if(null == roleId){
                return Result.err("未获取到角色信息");
            }
            List<Long> longs = MenuRight.create()
                    .select(MENU_RIGHT.MENU_ID)
                    .where(MENU_RIGHT.KIND.eq(1).and(MENU_RIGHT.RELL_ID.eq(roleId)))
                    .and(MENU_RIGHT.STATUS.eq(1))
                    .listAs(Long.class);
            if(longs.size()>0){
                QueryWrapper qw = QueryWrapper.create();
                qw.where(MENUS.PARENT_ID.eq(0))
                        .and(MENUS.KIND.eq(1))
                        .and(MENUS.STATUS.eq(1))
                        .and(MENUS.MENU_TYPE.in(new int[]{1,2}))
                        .and(MENUS.ID.in(longs))
                        .orderBy(MENUS.SORT_NUM,true);
                menus = menusMapper.selectListByQuery(qw);
                if(menus.size()>0){
                    for(Menus e : menus){
                        QueryWrapper cqw = QueryWrapper.create();
                        cqw.where(MENUS.PARENT_ID.eq(e.getId()))
                                .and(MENUS.STATUS.eq(1))
                                .and(MENUS.MENU_TYPE.in(new int[]{1,2}));
                        if(longs.size()>0){
                            cqw.and(MENUS.ID.in(longs));
                        }
                        cqw.orderBy(MENUS.SORT_NUM,true);
                        List<Menus> list = menusMapper.selectListByQuery(cqw);
                        if(list.size()>0){
                            for(Menus btn : list){
                                QueryWrapper bq = QueryWrapper.create();
                                bq.where(MENUS.PARENT_ID.eq(btn.getId()))
                                        .and(MENUS.STATUS.eq(1))
                                        .and(MENUS.MENU_TYPE.in(new int[]{3}));
                                bq.orderBy(MENUS.SORT_NUM,true);
                                List<Menus> btns = menusMapper.selectListByQuery(bq);
                                btn.setChildren(btns);
                            }
                        }
                        e.setChildren(list);
                    }
                }
            }
        }
        else{
            return Result.err("非法请求");
        }

        return Result.ok(menus);
    }


    @Log("保存菜单")
    @RequestMapping("/save")
    public Result save(@RequestBody Menus menu){
        Long userId = getUserId();
        if(null == menu.getId()){
            menu.setCreateId(userId);
        }
        menu.setUpdateId(userId);
        //设置默认值
        menu.setKind(1);
        menu.setStatus(1);
        menu.setIsCharge(0);
        int i = menusMapper.insertOrUpdate(menu);
        if(i>0){
            return  Result.ok();
        }
        return Result.err();
    }


    @Log("删除菜单")
    @RequestMapping("/delMenu")
    public Result delMenu(Long id){
        if(null == id){
            return Result.err("未获取到菜单ID");
        }
        boolean flag = Menus.create()
                .setId(id)
                .setStatus(0)
                .setUpdateId(getUserId())
                .updateById();
        if(flag){
            return Result.ok();
        }
        return Result.err();
    }

}
